package com.blobfish.customer;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.blobfish.kit.FileKit;
import com.blobfish.kit.TranslatedCacheUtil;

import java.io.File;
import java.util.List;

/**
 * 翻译指定文件
 * @author huangbo
 */
public class EnJsonFilerCreater {

    public static void main(String[] args) {
        List<File> fileList = FileKit.listTranslateFile();
        for (File file:
                fileList) {
            String langValueStr = FileUtil.readUtf8String(file);
            langValueStr = langValueStr.substring(15);
            langValueStr = langValueStr.replaceAll("(?<!:)\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/", "");
            JSONObject obj = JSONUtil.parseObj(langValueStr);
            translate(obj);
            String jsonStr = "export default " + JSONUtil.formatJsonStr(JSONUtil.toJsonStr(obj));
            cn.hutool.core.io.FileUtil.writeUtf8String(jsonStr, fileList.get(0).getAbsolutePath().replace("zh", "en"));
        }
    }

    private static void translate(Object obj) {
        if (obj instanceof JSONObject) {
            final JSONObject tmpObj = (JSONObject) obj;
            for (final String key : tmpObj.keySet()) {
                if (tmpObj.get(key) instanceof String) {
                    int retryNum = 3;
                    String resultStr = tmpObj.get(key).toString();
                    if (StrUtil.isNotBlank(resultStr)) {
                        resultStr = TranslatedCacheUtil.getResult(resultStr);
                    }
                    tmpObj.put(key, resultStr);
                } else {
                    translate(tmpObj.get(key));
                }
            }
        } else if (obj instanceof JSONArray) {
            JSONArray tmpArray = (JSONArray) obj;
            for (Object item : tmpArray) {
                translate(item);
            }
        }
    }
}
